<template>
  <ex-dialog width="1000px" class="ex-diolog" :title="title" :visible="visible" :close-on-click-modal="false"
    @closeDialog="handleClose">
    <div class="main" v-loading="loading">
      <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="140px" class="demo-ruleForm">
        <el-form-item label="已选日期：">
          <div class="dateTextList">
            <div class="dateWord">{{ isDownUp ? dateWordText.slice(0, 59) : dateWordText }}</div>
            <div class="dateBut" v-if="isWordLength" @click="wordLengthFunc">
              <i class="el-icon-arrow-down" v-if="isDownUp"></i>
              <i class="el-icon-arrow-up" v-else></i>
            </div>
          </div>
        </el-form-item>
        <el-form-item label="选择直播间：" prop="">
          <el-row>
            <el-col :span="15" class="roomSelect">
              <el-select v-model="ruleForm.roomList" placeholder="请选择" reserve-keyword multiple value-key="roomId"
                @change="roomChange" v-default-select="[liveRoomIdLs, typeDefault]">
                <el-option v-for="item in liveRoomList" :key="item.roomId" :label="item.name" :value="item"
                  :disabled="item.disabled">
                </el-option>
              </el-select>
            </el-col>
          </el-row>
        </el-form-item>
        <div v-for="(father, fatherIndex) in ruleForm.roomList" :key="fatherIndex">
          <el-form-item :label="father.name + '：'">
            <el-row v-for="(child, childIndex) in father.sessionList" :key="childIndex" class="mb20">
              <el-col :span="4">第{{ child.sessionNo }}场 {{ child.startTime }}-{{ child.endTime }}</el-col>
              <el-col :span="7" class="mr10">
                <el-select v-model="child.anchorIds" placeholder="请选择主播" multiple :disabled="child.disabled"
                  @change="roomChangeAnchor($event, fatherIndex, child)">
                  <el-option v-for="item in child.anchorIDList" :key="item.id" :label="item.value" :value="item.id"
                    :disabled="item.disabled && item.disabled == true">
                  </el-option>
                </el-select>
              </el-col>
              <el-col :span="7" class="mr10">
                <el-select v-model="child.controlIds" placeholder="请选择中控" multiple :disabled="child.disabled"
                  @change="roomChangeCentralControl($event, fatherIndex, child)">
                  <el-option v-for="item in child.centralControlIDList" :key="item.id" :label="item.value"
                    :value="item.id" :disabled="item.disabled && item.disabled == true">
                  </el-option>
                </el-select>
              </el-col>
              <el-col :span="2">
                <el-button type="text"
                  v-if="child.disabled == false && child.anchorIds.length > 0 && child.controlIds.length > 0"
                  @click="emptyData(fatherIndex, childIndex)">清空</el-button>
              </el-col>
            </el-row>
          </el-form-item>
        </div>

      </el-form>
    </div>
    <div class="button_box">
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" :loading="AgreeLoading" @click="submitForm('ruleForm')"
        :disabled="!(ruleForm.roomList && ruleForm.roomList.length > 0)">确认</el-button>
    </div>
  </ex-dialog>
</template>
<script>
import Loading from "@/components/Loading/index";
// api
import {
  workforceRoomSelectList, workforceRoomSessionList, setWorkforce, editWorkforce, workforceDetail, workforceUserSelectList
} from "@/api/customer/scheduleList";
import { parseTime } from '@/utils/index.js'
export default {
  components: {
    Loading
  },
  props: {
    visible: Boolean,
    dateIdLs: [String, Array],
    pathType: String,
  },
  data() {
    return {
      labelWidth: "150px",
      inputWidth: "420px",
      title: "设置排班",
      loading: false,
      AgreeLoading: false,
      dateWordText: '',//
      centralControlIDList: [], //中控id列表
      anchorIDList: [], //主播id列表
      isWordLength: false,//判断字长度 显示隐藏
      isDownUp: true,//向上
      liveRoom: [],//
      liveRoomList: [],//选择直播间
      liveRoomIdLs: [],//选择直播间id列表
      roomSessionList: [],//直播场次信息
      typeDefault: '',//不可删除的id
      ruleForm: {
        dateList: [],
        roomList: [
          // {
          //   roomId: '',
          //   sessionList: [
          //     {
          //       anchorIds: [],
          //       controlIds: [],
          //       sessionId:''
          //     }
          //   ]
          // }
        ]
      },
      rules: {},
    };
  },
  created() {
    // console.log('this.dateIdLs', this.dateIdLs)
    this.ruleForm.dateList = this.dateIdLs
    this.formatDateFunc() //格式化所选日期
    this.getAnchorIDList()
    this.getCentralControlIDList()
    // this.getWorkforceRoomSessionList()
    if (this.pathType == 'add') {
      if (this.dateIdLs.length > 1) {
        this.title = '编辑排班（批量设置）'
      } else {
        this.title = '编辑排班（单一设置）'
      }
      this.liveRoomLs()
    } else {
      this.title = '编辑排班（编辑）'
      this.liveRoomLs(this.dateIdLs[0])
      this.getDataDetails()
    }
    this.isWordLength = this.wordLength(this.dateWordText)
  },

  methods: {
    // 直播间下拉
    async liveRoomLs(date = '') {
      this.loading = true
      var data = { date: date }
      try {
        var res = await workforceRoomSelectList(data)
        this.liveRoomList = res.result
        this.liveRoomList = this.setDataList(this.liveRoomList)
        // console.log('this.liveRoomList', this.liveRoomList)
        let typeDefault = []
        let liveRoomIdLs = []
        this.liveRoomList.forEach(vo => {
          if (vo.disabled) {
            typeDefault.push(vo.roomId)
          }
          liveRoomIdLs.push(vo.roomId)
        })

        this.typeDefault = typeDefault
        this.liveRoomIdLs = liveRoomIdLs
        this.loading = false
      } catch (error) {
        this.loading = false
      }

      // console.log('this.typeDefault',this.typeDefault)
      // console.log('this.liveRoomIdLs',this.liveRoomIdLs)
    },
    // 获取直播场次
    // async getWorkforceRoomSessionList() {
    //   var res = await workforceRoomSessionList()
    //   this.roomSessionList = res.result
    //   this.roomSessionList = this.roomSessionList.map(element => {
    //     element.anchorIds = []
    //     element.controlIds = []
    //     element.disabled = false
    //     element.sessionId = element.id
    //     return element
    //   })
    //   // console.log('this.roomSessionList', this.roomSessionList)
    // },
    // 清空数据
    emptyData(fatherIndex, childIndex) {
      this.ruleForm.roomList[fatherIndex].sessionList[childIndex].anchorIds = []
      this.ruleForm.roomList[fatherIndex].sessionList[childIndex].controlIds = []
      this.changeDataFunc()
    },
    // 查看详情
    getDataDetails() {
      let params = {
        date: this.dateIdLs[0]
      }
      workforceDetail(params).then(response => {
        this.ruleForm.roomList = response.result.roomDetailVOS
        this.ruleForm.roomList = this.setDataList(this.ruleForm.roomList)
        this.changeDataFunc()
        // console.log('response.result.roomDetailVOS', this.ruleForm)
      })
    },
    // 添加主播、中控列表人员
    setDataList(data) {
      var dataList = []
      dataList = data.map(res => {
        res.sessionList = res.sessionList.map(vo => {
          vo.centralControlIDList = JSON.parse(JSON.stringify(this.centralControlIDList));  //深拷贝 
          vo.anchorIDList = JSON.parse(JSON.stringify(this.anchorIDList));
          return vo
        })
        return res
      })
      return dataList
    },
    // 主播选项改变
    roomChangeAnchor(e, fatherIndex, childIndex) {
      this.changeDataFunc()
    },
    // 中控选项改变
    roomChangeCentralControl(e, fatherIndex, childIndex) {
      this.changeDataFunc()
    },
    // 选择直播间改变
    roomChange(row) {
      this.changeDataFunc()
    },
    // 同一直播日期和同一场次，主播出现在不同直播间////同一直播日期和同一场次，中控人员出现在不同直播间
    changeDataFunc() {
      // 处理回显数据id
      this.ruleForm.roomList.forEach((oneRes, oneIndex) => {
        oneRes.sessionList.forEach((twoRes, twoIndex) => {
          let anchorIdsData = []
          let controlIdsData = []
          this.ruleForm.roomList.forEach((oneYRes, oneYIndex) => {
            if (oneIndex != oneYIndex) {
              oneYRes.sessionList.forEach((twoYRes, twoYIndex) => {
                if (!this.checkTime(twoRes.startTime, twoRes.endTime, twoYRes.startTime, twoYRes.endTime)) {
                  anchorIdsData = anchorIdsData.concat(twoYRes.anchorIds)
                  controlIdsData = controlIdsData.concat(twoYRes.controlIds)
                }
              })
            }
          })
          twoRes.anchorIdsData = anchorIdsData
          twoRes.controlIdsData = controlIdsData
        })
      })
      // console.log('this.ruleForm.roomList233', this.ruleForm.roomList)
      this.ruleForm.roomList.forEach((oneRes, oneIndex) => {
        oneRes.sessionList.forEach((twoRes, twoIndex) => {
          this.ruleForm.roomList.forEach((oneYRes, oneYIndex) => {
            // 跳过相同位置比较
            if (oneIndex != oneYIndex) {
              oneYRes.sessionList.forEach((twoYRes, twoYIndex) => {
                // 判断两个时间段是否存在交集
                if (!this.checkTime(twoRes.startTime, twoRes.endTime, twoYRes.startTime, twoYRes.endTime)) {
                  // console.log('twoRes.startTime,twoRes.endTime',twoRes.startTime,twoRes.endTime)
                  // console.log('twoYRes.startTime,twoYRes.endTime',twoYRes.startTime,twoYRes.endTime)
                  // 重置主播可选项
                  twoYRes.anchorIDList.forEach(alis => {
                    if (twoRes.anchorIdsData.findIndex(obj => obj == alis.id) == -1) {
                      alis.disabled = false
                    }
                  })
                  // 重置中控可选项
                  twoYRes.centralControlIDList.forEach(alis => {
                    if (twoRes.controlIdsData.findIndex(obj => obj == alis.id) == -1) {
                      alis.disabled = false
                    }
                  })

                  // 主播存在交集且有选值 给定不可选
                  if (twoRes.anchorIds.length > 0) {
                    twoRes.anchorIds.forEach((anchorRes, anchorIndex) => {
                      var index = twoRes.anchorIDList.findIndex(obj => obj.id == anchorRes)
                      twoYRes.anchorIDList[index].disabled = true
                    })
                  }
                  // 中控存在交集且有选值 给定不可选
                  if (twoRes.controlIds.length > 0) {
                    twoRes.controlIds.forEach((controlRes, controlIndex) => {
                      var index = twoRes.centralControlIDList.findIndex(obj => obj.id == controlRes)
                      twoYRes.centralControlIDList[index].disabled = true
                    })
                  }
                }
              })
            }
          })
        })
      })
      // console.log('this.ruleForm.roomList', this.ruleForm.roomList)
    },
    //主播id列表
    async getAnchorIDList() {
      this.anchorIDList = await this.getRoleTypeLs(1)
    },
    //中控id列表
    async getCentralControlIDList() {
      this.centralControlIDList = await this.getRoleTypeLs(2)
    },
    //1 主播 2 中控
    getRoleTypeLs(roleType) {
      return new Promise((resolve, reject) => {
        var params = { roleType, date: parseTime(this.dateIdLs[0], '{y}-{m}') }
        workforceUserSelectList(params).then((res) => {
          resolve(res.result);
        })
      })
    },
    // 格式化所选日期
    formatDateFunc() {
      if (this.dateIdLs && this.dateIdLs.length > 0) {
        let array = []
        this.dateIdLs.forEach(element => {
          let month = new Date(element)
          array.push(`${month.getMonth() + 1}月${month.getDate()}日`)
        });
        this.dateWordText = array.join('、')
      }
    },
    // 计算字体长度
    wordLength(text) {
      let status = false
      if (text && text.length > 59) status = true
      return status
    },
    // 点击上下键显示按钮
    wordLengthFunc() {
      this.isDownUp = !this.isDownUp
    },
    //取消
    handleClose(formName) {
      this.$emit("update:visible", false);
      this.$emit("clearId");
    },
    // 确认添加数据
    submitForm(formName) {
      if (this.ruleForm.roomList && this.ruleForm.roomList.length > 0) {
        let status = this.ruleForm.roomList.every(res => {
          return res.sessionList.every(vo => {
            if (vo.anchorIds.length > 0 && vo.controlIds.length == 0) {
              this.$message.error('请选择中控')
              return false
            } else if (vo.anchorIds.length == 0 && vo.controlIds.length > 0) {
              this.$message.error('请选择主播')
              return false
            }
            return true
          })
        })
        console.log('status', status)
        if (status == false) {
          return
        }
      }
      console.log('this.pathType', this.pathType)
      //创建确定
      this.$refs[formName].validate(valid => {
        if (valid) {
          if (this.pathType == 'edit') {
            this.editData()
          } else {
            this.addData()
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    // 设置场次
    addData() {
      this.AgreeLoading = true
      var data = {
        ...this.ruleForm
      }
      setWorkforce(data).then(res => {
        this.$message.success('添加成功')
        setTimeout(() => {
          this.handleClose()
          this.$emit('success')
          this.AgreeLoading = false
        }, 1000);
      }).finally(() => {
        this.AgreeLoading = false
      })
    },
    // 编辑场次
    editData() {
      this.AgreeLoading = true
      var data = {
        date: this.dateIdLs[0],
        roomEditDTOS: this.ruleForm.roomList
      }
      console.log('data', data)
      editWorkforce(data).then(res => {
        this.$message.success('修改成功')
        setTimeout(() => {
          this.handleClose()
          this.$emit('success')
          this.AgreeLoading = false
        }, 1000);
      }).finally(() => {
        this.AgreeLoading = false
      })
    },
    // 判断两个时间是否有交集
    checkTime(a, b, x, y) {
      var times1 = [], times2 = [];
      if (a < b) {
        //未跨天
        times1.push([a, b]);
      } else {
        //跨天
        times1.push([a, "24:00"], ["00:00", b]);
      }

      if (x < y) {
        times2.push([x, y]);
      } else {
        times2.push([x, "24:00"], ["00:00", y]);
      }

      var flag = false;
      //循环比较时间段是否冲突
      for (var i = 0; i < times1.length; i++) {
        if (flag) break;
        for (var j = 0; j < times2.length; j++) {
          if (this.check(times1[i][0], times1[i][1], times2[j][0], times2[j][1])) {
            flag = true;
            break;
          }
        }
      }
      if (flag) {
        console.log("发生冲突");
        return false;
      } else {
        console.log("没有冲突");
        return true;
      }
    },
    check(a, b, x, y) {
      if (y <= a || b <= x) {
        return false;
      } else {
        return true;
      }
    }
  }
};
</script>
<style lang="scss" scoped>
.ex-diolog {
  ::v-deep .ex--dialog--footer {
    border: none !important;
    padding: 0 !important;
  }

  ::v-deep .ex--dialog--main {
    padding: 10px 20px !important;

    .el-select {
      width: 100%;
    }
  }
}

.main {
  padding: 20px 20px;
}

.button_box {
  display: flex;
  justify-content: center;

}

.dateTextList {
  display: flex;
  flex-direction: row;
  align-items: flex-start;
}

.dateWord {
  width: 695px;
  margin-right: 5px
}

.dateBut {
  width: 20px;
  height: 35px;
  display: flex;
  align-items: center;
}

.mr10 {
  margin-right: 10px;
}

.mb20 {
  margin-bottom: 20px;
}

::v-deep {
  .mb20 {
    .el-tag--light {
      display: flex;
      align-items: center;

      .el-select__tags-text {
        max-width: 150px;
        display: inline-block;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
    }

  }
}
</style>
